package com.holyn.guofang.view.distinguish;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.bumptech.glide.Glide;
import com.holyn.guofang.R;
import com.holyn.guofang.view.BaseActivity;
import com.holyn.guofang.viewcommon.crop.CropActivity;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;

/**
 * Created by Holyn on 2019/1/18 10:14 PM.
 */
public class PictureConfirmActivity extends BaseActivity {

    public static final int REQUEST_CODE_OPEN_ALBUM = 0x0001;
    public static final int REQUEST_CODE_TAKE_PHOTO = 0x0002;
    public static final int REQUEST_CODE_CROP_IMAGE = 0x0003;

    public static final String INTENT_KEY_REQUEST_CODE = "KEY_REQUEST_CODE";
    public static final String INTENT_KEY_IMAGE_PATH = "KEY_IMAGE_PATH";

    @BindView(R.id.tv_album)
    TextView tvAlbum;
    @BindView(R.id.tv_take_photo)
    TextView tvTakePhoto;
    @BindView(R.id.tv_crop)
    TextView tvCrop;
    @BindView(R.id.imageview)
    ImageView imageview;
    @BindView(R.id.btn_submit)
    Button btnSubmit;

    private Intent fromIntent;
    private int requestCode = -1;

    private String imagePath = "";

    public static void startForResult(Activity fromActivity, int requestCode) {
        Intent intent = new Intent(fromActivity, PictureConfirmActivity.class);
        intent.putExtra(INTENT_KEY_REQUEST_CODE, requestCode);
        fromActivity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_picture_confirm;
    }

    @Override
    protected void onMyCreate() {
        ButterKnife.bind(this);
        showToolbar("编辑图片");

        fromIntent = getIntent();
        requestCode = fromIntent.getIntExtra(INTENT_KEY_REQUEST_CODE, -1);
        if (requestCode == REQUEST_CODE_OPEN_ALBUM){
            openAlbum();
        } else if (requestCode == REQUEST_CODE_TAKE_PHOTO){
            takePhoto();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtils.d("onActivityResult");
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                    imagePath = selectList.get(0).getCompressPath();
                    Glide.with(PictureConfirmActivity.this).load(imagePath)
//                            .error(R.drawable.ic_empty_image)
                            .into(imageview);
                    break;
                case REQUEST_CODE_CROP_IMAGE:
                    imagePath = data.getStringExtra(CropActivity.EXTRA_RESULT_CROP_PATH);
                    Glide.with(PictureConfirmActivity.this).load(imagePath)
//                            .error(R.drawable.ic_empty_image)
                            .into(imageview);
                    break;
            }
        } else {
            PictureConfirmActivity.this.finish();
        }
    }

    @OnClick({R.id.tv_album, R.id.tv_take_photo, R.id.tv_crop, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_album:
                openAlbum();
                break;
            case R.id.tv_take_photo:
                takePhoto();
                break;
            case R.id.tv_crop:
                imageCrop();
                break;
            case R.id.btn_submit:
                fromIntent.putExtra(INTENT_KEY_IMAGE_PATH, imagePath);
                setResult(Activity.RESULT_OK, fromIntent);
                PictureConfirmActivity.this.finish();
                break;
        }
    }

    private void openAlbum() {
        PictureSelector.create(PictureConfirmActivity.this)
                .openGallery(PictureMimeType.ofImage())
                .isCamera(false)
                .selectionMode(PictureConfig.SINGLE)
                .compress(true)// 是否压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);

    }

    private void takePhoto() {
        new RxPermissions(PictureConfirmActivity.this)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(@NonNull Boolean aBoolean) throws Exception {
                        PictureSelector.create(PictureConfirmActivity.this)
                                .openCamera(PictureMimeType.ofImage())
                                .selectionMode(PictureConfig.SINGLE)
                                .imageFormat(".jpg")
                                .compress(true)// 是否压缩
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                    }
                });

    }

    private void imageCrop(){
        new RxPermissions(PictureConfirmActivity.this)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.INTERNET)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(@NonNull Boolean aBoolean) throws Exception {
                        if (aBoolean){
                            Uri sourceUri = Uri.fromFile(new File(imagePath));
                            startActivityForResult(CropActivity.callingIntent(PictureConfirmActivity.this, sourceUri), REQUEST_CODE_CROP_IMAGE);

                        }
                    }
                });
    }
}
